package com.ruoyi.common.utils.modbus;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TcpToSerialClient {

    static Log log = LogFactory.getLog(TcpToSerialClient.class);

    public static void main(String[] args) {
        String serverIp = "127.0.0.1"; // 串口服务器的IP地址
        int serverPort = 18888; // 串口服务器的端口号

        for (int i = 0; i < 10; i++) {
            String responseData = sendData(serverIp, serverPort, "串口服务器的端口号14");
            System.out.println(responseData);
        }

    }

    public static String getData(String serverIp, int serverPort) {
        String responseData = null;
        Socket socket = null;
        InputStream inputStream = null;
        try {
            // 建立TCP连接
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverIp, serverPort), 3000); // 3秒连接超时
            socket.setSoTimeout(5000); // 5秒读写超时

            // 获取输入流和输出流
            inputStream = socket.getInputStream();
//            OutputStream outputStream = socket.getOutputStream();

            // 发送数据到串口设备
//            String dataToSend = "Hello, Serial Device!";
//            outputStream.write(dataToSend.getBytes());
//            log.info("【dataUpload】Sent data to serial device: " + dataToSend);

            // 接收串口设备的响应数据
            byte[] buffer = new byte[1024];
            int bytesRead = inputStream.read(buffer);
            if (bytesRead > 0) {
                responseData = new String(buffer, 0, bytesRead);
            }

        } catch (IOException e) {
            log.error("【dataUpload】【0183】异常 : " + e.getMessage());
        } finally {
            // 确保关闭所有资源
            try {
                if (inputStream != null) inputStream.close();
            } catch (IOException e) {
                log.error("【dataUpload】【sendData】关闭输入流时出错: " + e.getMessage());
            }

            try {
                if (socket != null && !socket.isClosed()) {
                    socket.close();
                }
            } catch (IOException e) {
                log.error("【dataUpload】【sendData】关闭连接时出错: " + e.getMessage());
            }
        }
        return responseData;
    }

    public static String sendData(String serverIp, int serverPort, String dataToSend) {
        String responseData = null;
        Socket socket = null;
        OutputStream outputStream = null;

        try {
            // 建立TCP连接
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverIp, serverPort), 3000); // 3秒连接超时
            socket.setSoTimeout(5000); // 5秒读写超时

            // 获取输出流
            outputStream = socket.getOutputStream();

            // 1. 使用标准的ASCII换行符 (推荐)
            String messageWithNewline = dataToSend + "\r\n";

            // 发送数据到服务器 Charset.forName("GB2312")
            outputStream.write(messageWithNewline.getBytes(StandardCharsets.UTF_8));

            // 确保数据立即发送
            outputStream.flush();

            // 接收服务器的响应数据 (如果需要)
//             InputStream inputStream = socket.getInputStream();
//             byte[] buffer = new byte[1024];
//             int bytesRead = inputStream.read(buffer);
//             if (bytesRead > 0) {
//                 responseData = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);
//             }

        } catch (IOException e) {
            log.error("【dataUpload】【0183】输出异常 : " + e.getMessage());
            responseData = e.getMessage();
        } finally {
            // 确保关闭所有资源
            try {
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                log.error("【dataUpload】【sendData】关闭输出流时出错: " + e.getMessage());
                responseData = e.getMessage();
            }

            try {
                if (socket != null && !socket.isClosed()) {
                    socket.close();
                }
            } catch (IOException e) {
                log.error("【dataUpload】【sendData】关闭连接时出错: " + e.getMessage());
                responseData = e.getMessage();
            }
        }
        return responseData;
    }

    // 在 TcpToSerialClient 中添加直接发送字节数组的方法
    public static String sendFrame(String serverIp, int serverPort, byte[] frame) {
        String responseData = null;
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null; // 用于接收响应（如果需要）
        try {
            // 建立TCP连接
            socket = new Socket();
            socket.connect(new InetSocketAddress(serverIp, serverPort), 3000); // 3秒连接超时
            socket.setSoTimeout(5000); // 5秒读写超时

            // 获取输出流并发送帧数据
            outputStream = socket.getOutputStream();
            outputStream.write(frame); // 直接发送原始字节数组（帧数据）
            outputStream.flush(); // 确保数据立即发送
//            log.info("发送帧成功，长度: " + frame.length + " 字节");

            // （可选）如果需要接收设备响应，添加以下代码
//            inputStream = socket.getInputStream();
//            byte[] responseBuffer = new byte[1024];
//            int bytesRead = inputStream.read(responseBuffer);
//            if (bytesRead > 0) {
//                responseData = "接收响应: " + FrameBuilder.bytesToHex(Arrays.copyOf(responseBuffer, bytesRead));
//            }

        } catch (IOException e) {
            log.error("发送帧异常: " + e.getMessage());
            responseData = "发送失败: " + e.getMessage();
        } finally {
            // 关闭资源
            try {
                if (inputStream != null) inputStream.close();
            } catch (IOException e) {
                log.error("关闭输入流失败: " + e.getMessage());
            }
            try {
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                log.error("关闭输出流失败: " + e.getMessage());
            }
            try {
                if (socket != null && !socket.isClosed()) socket.close();
            } catch (IOException e) {
                log.error("关闭连接失败: " + e.getMessage());
            }
        }
        return responseData;
    }

}
